<?php

class BackendController extends BaseController
{
    public function init()
    {
        $this->authFrom = 'backend';
    }

    /**
     * Filters
     * @return array
     */
    public function filters()
    {
        $filters = array(
            'accessControl', // simple built-in auth checks
        );
        return array_merge($filters, parent::filters());
    }

    /**
     * Access rules
     * @return array
     */
    public function accessRules()
    {
        return array(
            // Allow login action for guests
            array('allow',
                'actions'=>array('login'),
                'controllers'=>array('backendsite'),
                'users'=>array('?'),
            ),
            // Deny all from guests
            array('deny',
                'users'=>array('?'),
            ),
        );
    }

    /**
     * @param CAction $action
     * @return bool
     */
    public function beforeAction($action)
    {
        $this->_adminAction(Yii::app()->user->id, Yii::app()->controller->id, Yii::app()->controller->action->id);
        return $this->_checkAccess(Yii::app()->controller->id, Yii::app()->controller->action->id);
    }

    /**
     * @param integer $admin_id
     * @param string $controller_name
     * @param string $action_name
     * @return bool
     */
    private function _adminAction($admin_id, $controller_name, $action_name)
    {
        if (!Yii::app()->user->isGuest) {
            $accessKey = $controller_name.'/'.$action_name;
            $time = date("Y-m-d H:i:s");
            $admin_model = new BackendAdminAction();
            $arr_accessKey = array('backendsite/error', 'backendsite/index', 'backendsite/logout', 'backendsite/login');
            if (!in_array($accessKey, $arr_accessKey)) {
                if ($admin_model->add($admin_id, $time, $accessKey) > 0) {
                    return true;
                }
            }
        }
    }

    /**
     * @throws CHttpException
     * @param string $controller_name
     * @param string $action_name
     * @return bool
     */
    private function _checkAccess($controller_name, $action_name)
    {
        $accessKey = $controller_name.'/'.$action_name;
        $arr_accessKey = array('backendsite/error', 'backendsite/index', 'backendsite/logout', 'backendsite/login');
        if ((Yii::app()->user->checkAccess($accessKey)) OR (in_array($accessKey, $arr_accessKey))) {
            return true;
        } else {
            throw new CHttpException(403, Yii::t('backendsite_error', 'ACCESSDENIED'));
        }
    }
}